package com.qc31.monitorlib.ui.simplemonitor

import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import autodispose2.autoDispose
import com.qc31.baselib.auto.AutoDisposeViewModel
import com.qc31.baselib.utils.ArrayUtil
import com.qc31.baselib.utils.CacheMMKV
import com.qc31.comlib.UserConstant
import com.qc31.comlib.entity.GpsDetail
import com.qc31.comlib.net.ServiceHelper
import com.qc31.monitorlib.R
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.subjects.PublishSubject

/** @Author Jasper @Time 2021/3/16 @Desc todo */
class SimpleMonitorViewModel : AutoDisposeViewModel() {
    //车队ID
    var isTimeShow: Boolean
    var isStateShow: Boolean
    var isSpeedShow: Boolean
    var isDriverShow: Boolean
    var isMileShow: Boolean
    var isRunStopShow: Boolean

    var teamId = ""
    var isClear = false
    private val allCas = ArrayList<GpsDetail>()
    private var mCarsHandle: UpdateHandle? = null
    private val mCarsHandleThread: HandlerThread by lazy { HandlerThread("mListHandleThread") }
    private val carsSub by lazy { PublishSubject.create<MutableList<GpsDetail>>() }

    fun carsObserver(): Observable<MutableList<GpsDetail>> = carsSub.hide()

    init {
        initThread()

        isTimeShow = CacheMMKV.decodeBoolean("isTimeShowS", true)
        isStateShow = CacheMMKV.decodeBoolean("isStateShowS", true)
        isSpeedShow = CacheMMKV.decodeBoolean("isSpeedShowS", true)
        isDriverShow = CacheMMKV.decodeBoolean("isDriverShowS", true)
        isMileShow = CacheMMKV.decodeBoolean("isMileShowS", true)
        isRunStopShow = CacheMMKV.decodeBoolean("isRunStopShowS", true)
    }

    /** 初始化线程 */
    private fun initThread() {
        mCarsHandleThread.start()
        mCarsHandle = UpdateHandle(mCarsHandleThread.looper)
    }

    /** 停止线程 */
    private fun stopThread() {
        mCarsHandle?.removeCallbacksAndMessages(null)
        mCarsHandleThread.quit()
    }

    /** 排序方式 */
    var sortByType: String
        get() = CacheMMKV.decodeString("sort_type_s", "carPlate")
        set(value) {
            CacheMMKV.encode("sort_type_s", value)
            refreshData()
        }

    /** 刷新数据 */
    private fun refreshData() {
        if (allCas.size > 0) {
            val msg = Message.obtain()
            msg.obj = allCas
            msg.what = 1
            mCarsHandle?.sendMessage(msg)
        }
    }


    /** 查询定位数据 */
    fun getCarsLocation() {
        if (isClear || UserConstant.current_car_num > 300 && teamId.isEmpty()) {
            toast(R.string.toast_choose_team)
            return
        }
        toastLoading(true)
        ServiceHelper.getRepository().getGpsRInfo(teamId, "").autoDispose(this)
            .subscribe({
                toastLoading(false)
                val msg = Message.obtain()
                msg.obj = it
                msg.what = 0
                mCarsHandle?.sendMessage(msg)
            }, error)
    }

    /** 通过车辆Id获取定位信息 */
    private fun getLocationsByCarIds(carIds: String) {
        ServiceHelper.getRepository().getGpsRInfo("", carIds).autoDispose(this)
            .subscribe({
                toastLoading(false)
                val msg = Message.obtain()
                msg.obj = it
                msg.what = 0
                mCarsHandle?.sendMessage(msg)
            }, error)
    }

    internal inner class UpdateHandle(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 0) {
                var locations = msg.obj as MutableList<GpsDetail>
                locations = ArrayUtil.sortBy(
                    locations,
                    sortByType,
                    true
                ) as MutableList<GpsDetail>
                carsSub.onNext(locations)
            } else if (msg.what == 1) {
                val locations = msg.obj as MutableList<GpsDetail>
                handleRefresh(locations)
            }
        }
    }

    /** 刷新 */
    fun refresh(locations: MutableList<GpsDetail>) {
        if (locations.size <= 0) return
        val msg = Message.obtain()
        msg.obj = locations
        msg.what = 1
        mCarsHandle?.sendMessage(msg)
    }

    private val stringBuilder = StringBuilder()
    private fun handleRefresh(locations: MutableList<GpsDetail>) {
        toastLoading(true)
        stringBuilder.setLength(0)
        for (location in locations) {
            stringBuilder.append(location.carId)
            stringBuilder.append(",")
        }
        if (stringBuilder.length > 1) {
            stringBuilder.deleteAt(stringBuilder.lastIndex)
            val carIds = stringBuilder.toString()
            getLocationsByCarIds(carIds)
        } else {
            toastLoading(false)
        }

    }

    fun setTime(isTimeShow: Boolean) {
        this.isTimeShow = isTimeShow
        CacheMMKV.encode("isTimeShowS", isTimeShow)
    }

    fun setState(isStateShow: Boolean) {
        this.isStateShow = isStateShow
        CacheMMKV.encode("isStateShowS", isStateShow)
    }

    fun setSpeed(isSpeedShow: Boolean) {
        this.isSpeedShow = isSpeedShow
        CacheMMKV.encode("isSpeedShowS", isSpeedShow)
    }

    fun setDriver(isDriverShow: Boolean) {
        this.isDriverShow = isDriverShow
        CacheMMKV.encode("isDriverShowS", isDriverShow)
    }

    fun setMile(isMileShow: Boolean) {
        this.isMileShow = isMileShow
        CacheMMKV.encode("isMileShowS", isMileShow)
    }

    fun setRunStop(isRunStopShow: Boolean) {
        this.isRunStopShow = isRunStopShow
        CacheMMKV.encode("isRunStopShowS", isRunStopShow)
    }


    override fun onCleared() {
        super.onCleared()
        stopThread()
    }
}
